<template>
  <div class="container">
    <h1>用户登录</h1>
    <el-form ref="formRef" :model="account" :rules="rules" label-width="60px" status-icon>
      <el-form-item label="用户名" prop="username">
        <el-input type="text" v-model="account.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="account.password"></el-input>
      </el-form-item>
      <el-form-item label="验证码" >
        <el-input type="text" v-model="account.captcha"></el-input>
        <el-image style="width: 120px; height: 38px" :src="captchaImageBase64Data" @click="getCaptcha" />
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="login">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import accountApi from '@/api/accountApi';
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import router from '@/router';
import { useTokenStore } from '@/stores/token';

const tokenStore = useTokenStore();

const account = ref({
  username: '',
  password: '',
  captchaId: '',
  captcha: ''
});

const captchaImageBase64Data = ref('');

// 校验用户名
const validateUsername = (rule, value, callback) => {
  const usernameRegex = /^[a-zA-Z0-9]{1,9}$/;
  if (!value) {
    return callback(new Error('请输入用户名'));
  } else if (!usernameRegex.test(value)) {
    return callback(new Error('用户名只能包含字母或数字，且长度不能超过9位'));
  } else {
    callback();
  }
};

// 校验密码
const validatePassword = (rule, value, callback) => {
  const passwordRegex = /^[0-9]{1,9}$/;
  if (!value) {
    return callback(new Error('请输入密码'));
  } else if (!passwordRegex.test(value)) {
    return callback(new Error('密码只能是数字，且长度不能超过9位'));
  } else {
    callback();
  }
};

const rules = reactive({
  username: [{ validator: validateUsername, trigger: 'blur' }],
  password: [{ validator: validatePassword, trigger: 'blur' }],
});

// 处理登录逻辑
function login() {
  const form = formRef.value;
  if (!form) return;

  form.validate((valid) => {
    // if (!valid) {
    //   ElMessage.error('请检查输入的用户名和密码格式');
    //   return;
    // }

    accountApi.login(account.value)
     .then(resp => {
        if (resp.code === 10000) {
          // 弹出提示信息
          ElMessage.success({
            message: resp.msg,
            type: "success",
            duration: 1200,
            onClose: () => {
              // 获取用户权限
              accountApi.ps().then(resp => {
                if (resp.data.permissions === 1) {
                  router.push('/user');
                } else {
                  router.push('/index');
                }
              }).catch(error => {
                ElMessage.error('获取权限失败');
              });
            }
          });
          // 保存 jwt 到 sessionStorage
          sessionStorage.setItem("token", resp.data);
          tokenStore.update(resp.data);
        } else {
          ElMessage.error(resp.msg);
        }
      }).catch(error => {
        ElMessage.error('登录失败');
      });
  });
}

function getCaptcha() {
  accountApi.captcha()
    .then(resp => {
      account.value.captchaId = resp.data.captchaId;
      captchaImageBase64Data.value = resp.data.captchaImageBase64Data;
    });
}

getCaptcha();
const formRef = ref(null);
</script>

<style scoped>
.container {
    width: 300px;
    border: 1px solid black;
    border-radius: 5px;
    padding: 20px;
    padding-top: 0px;
    margin: auto;
    margin-top: 150px;
    background-color: lightskyblue;
     /* 添加背景图片相关样式 */
     background-image: url('img/f.png');
    background-size: cover;
    background-position: center;
}

</style>

<style>
body {
    /* 确保路径正确，这里假设图片在 public 文件夹下，如果不是请调整路径 */
    background-image: url('img/e.png');
    background-size: cover;
    background-position: center;
}
</style>